package com.op.lib;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.op.utils.IntKey;

public class Protocal {

    private HashMap<IntKey, String> mProtocals;

    private HashMap<String, IntKey> mNames;

    private IntKey                  mReuseKey;

    private String                  mKey;

    private String                  mData;

    public Protocal(String key, String data) {
        mKey = key;
        mData = data;

        mReuseKey = new IntKey(-1);
        mProtocals = new HashMap<IntKey, String>();
        mNames = new HashMap<String, IntKey>();
    }

    public Protocal put(int id, String name) {
        if (mProtocals.containsKey(mReuseKey.set(id))) {
            String oldname = mProtocals.get(mReuseKey.set(id));
            mNames.remove(oldname);
        }
        mProtocals.put(new IntKey(id), name);
        mNames.put(name, new IntKey(id));
        return this;
    }

    public int id(JSONObject obj) {
        return id(obj.optString(mKey));
    }

    public int id(String key) {
        IntKey id = mNames.get(key);
        if (id == null) {
            return -1;
        }
        return id._value;
    }

    public String key() {
        return mKey;
    }

    public String name(int id) {
        return mProtocals.get(mReuseKey.set(id));
    }

    public JSONObject createMessage(int id) throws JSONException {
        return new JSONObject().put(mKey, name(id));
    }

    public JSONObject createMessage(int id, JSONObject data) throws JSONException {
        return new JSONObject().put(mKey, name(id)).put(mData, data);
    }
}
